﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.Synchronization.Validation.Validators;

namespace Sustainalytics.Synchronization.Validation.Log
{
    class LogValidationResult : ILogClient
    {
        private readonly IMongoCollection<ValidationLog> mongoCollection;
        private readonly IMessageFormatter formatter;

        public LogValidationResult(IMongoCollection<ValidationLog> mongoCollection, IMessageFormatter formatter)
        {
            this.mongoCollection = mongoCollection;
            this.formatter = formatter;
        }

        public void WriteAsync(IEnumerable<ValidationFailure> messages)
        {
            if (!messages.Any())
                return;

            formatter.LoadAdditionalDataAsync(messages.Select(x => x.Key).Distinct()).Wait();
            
            var validationLogs = messages.Select(x =>
                    new ValidationLog
                    {
                        Id = new Guid(),
                        CompanyId = x.Key,
                        CapitalIqId = formatter.GetCorporateDataInfo(x).CapitalIqId,
                        CompanyName = formatter.GetCorporateDataInfo(x).CompanyName,
                        RuleCode = x.Code,
                        RuleComment = x.Comment,
                        Triggers = (x.Triggers != null && x.Triggers.Any()) ? string.Join("#", x.Triggers) : null,
                        ResearchProduct = x.ResearchProduct,
                        Date = DateTime.UtcNow.Date
                    });

            mongoCollection.InsertManyAsync(validationLogs).Wait();
        }
    }   
}
